package org.an.demo.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.Scroller;
import java.util.ArrayList;
import java.util.List;
import org.an.demo.module.WheelInfo;
import org.an.ku.util.DensityUtil;

/**
 * 创建时间：2017年04月07日17:48 <br>
 * 作者：fuchaoyang <br>
 * 描述：
 */

public class WheelView extends View {

  private Scroller mScroller;
  private int mTouchSlop;
  private List<? extends DataSet> mData;
  private int mLastDownY;
  private int mLastMotionY;
  private int mScrollOffsetY;
  private boolean mIsClick;
  private int mItemHeight, mHalfItemHeight;
  private Paint mPaint;
  private int mVisibleCount = 5, mDrawCount = 7;

  public WheelView(Context context) {
    super(context);
  }

  public WheelView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
  }

  private void init() {
    mScroller = new Scroller(getContext());
    ViewConfiguration configuration = ViewConfiguration.get(getContext());
    //mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration);
    mTouchSlop = 8;
    mItemHeight = DensityUtil.dip2px(getContext(), 45);
    System.out.println("mItemHeight = " + mItemHeight);
    mHalfItemHeight = (int) (mItemHeight / 2.f);
    mPaint = new Paint();
    mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
    mPaint.setColor(Color.GRAY);
    mPaint.setTextSize(DensityUtil.dip2px(getContext(), 15));

    mWheelInfos = new ArrayList<>();
    for (int i = 0; i < 20; i++) {
      mWheelInfos.add(new WheelInfo(String.format("%02d行", i)));
    }
    setData(mWheelInfos);
  }

  private List<WheelInfo> mWheelInfos;

  @Override public boolean onTouchEvent(MotionEvent ev) {
    switch (ev.getAction()) {
      case MotionEvent.ACTION_DOWN:
        System.out.println("========ACTION_DOWN=========");
        getParent().requestDisallowInterceptTouchEvent(true);
        if (!mScroller.isFinished()) {
          mScroller.abortAnimation();
        }
        mLastDownY = mLastMotionY = (int) ev.getY();
        break;
      case MotionEvent.ACTION_MOVE:
        if (Math.abs((int) ev.getY() - mLastDownY) < mTouchSlop) {
          // 认为是点击
          mIsClick = true;
          break;
        }

        mIsClick = false;
        int offset = mLastMotionY - (int) ev.getY();
        // 避免过度刷新
        if (Math.abs(offset) < 1) break;
        mScrollOffsetY += offset;
        mLastMotionY = (int) ev.getY();
        scrollBy(0, offset);
        //scrollTo(0,mScrollOffsetY);
        break;
      case MotionEvent.ACTION_UP:
        //getParent().requestDisallowInterceptTouchEvent(false);
        if (mIsClick) break;
        mScroller.startScroll(0, mScrollOffsetY, 0, computeDistanceToEndPoint());
        invalidate();
        break;
    }
    //return super.onTouchEvent(ev);
    // 默认返回值不是true吗，为啥写成super不对呢
    return true;
  }

  /**
   * 计算应该滑动的距离
   */
  private int computeDistanceToEndPoint() {
    int remainder = mScrollOffsetY % mItemHeight;
    if (Math.abs(remainder) > mHalfItemHeight) {
      if (mScrollOffsetY < 0) {
        return -mItemHeight - remainder;
      } else {
        return mItemHeight - remainder;
      }
    } else {
      return -remainder;
    }
  }

  private int mTextMaxWidth, mTextMaxHeight;

  private void computeTextSize() {
    mTextMaxWidth = (int) mPaint.measureText(mData.get(0).getText());
    Paint.FontMetrics metrics = mPaint.getFontMetrics();
    mTextMaxHeight = (int) (metrics.bottom - metrics.top);
  }

  public void setData(List<? extends DataSet> data) {
    mData = data;
    computeTextSize();
  }

  @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), mItemHeight * mVisibleCount);
  }

  // 当前选中的
  private int mSelectPos = 2;

  @Override protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    System.out.println("getHeight() = " + getHeight());

    //canvas.drawLine(0, mItemHeight * 2, getWidth(), mItemHeight * 2, mPaint);
    //canvas.drawLine(0, mItemHeight * 4, getWidth(), mItemHeight * 4, mPaint);
    // 绘制当前可见的item个数+2，因为上下一半一半
    for (int i = 0; i < mDrawCount; i++) {
      if (i != 0 || i != mDrawCount - 1) {
        // scrollBy后，内容移动，这个时候线的左边就发生了变化。
        canvas.drawLine(0, mItemHeight * i, getWidth(), mItemHeight * i, mPaint);
        System.out.println("------绘制线--------");
      }
      int y = (int) (mItemHeight * i + mHalfItemHeight + mTextMaxHeight / 2.f);
      canvas.drawText(mData.get(i).getText(), getWidth() / 2.f - mTextMaxWidth / 2, y, mPaint);
    }
  }

  @Override public void computeScroll() {
    if (mScroller.computeScrollOffset()) {
      System.out.println("computeScroll = ");
      scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
      invalidate();
    }
  }
}
